<template>
  <div class="container" v-show="menuList.length">
    <div class="header">
      <el-dropdown class="select">
        {{currentMenu.name}}
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-for="item in menuList" :key="item.id" @click="onSel(item)">
              {{item.name}}
              <SvgIcon
                icon="close1"
                style="cursor: pointer; font-size: 10px; fill: #000; margin-bottom: 2px; margin-left: 20px;"
                @click="onClose(item.id)"
              />
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <div>
        <SvgIcon
          style="cursor: pointer; margin-right: 4px"
          :icon="collapse ? 'show' : 'hide'"
          @click="collapse = !collapse"
        ></SvgIcon>
        <SvgIcon style="cursor: pointer;" icon="close" @click="onCloseAll"></SvgIcon>
      </div>
    </div>
    <div v-for="item in menuList" :key="item.id" v-show="currentMenu.id === item.id && !collapse">
      <tile v-if="item.type === '3dtiles'" :layerId="item.id"></tile>
      <model v-if="item.type === 'model'" :layerId="item.id"></model>
      <template v-if="item.type === 'favorites'">
        <rootCollection v-if="isRoot" :ref="setCollectionDom"></rootCollection>
        <normalCollection v-else :ref="setCollectionDom"></normalCollection>
      </template>
      <surfaceTransparency v-if="item.type === 'surfaceTransparency'"></surfaceTransparency>
      <tileLoadingConfig v-if="item.type === 'tileLoadingConfig'" :tileId="item.id"></tileLoadingConfig>
      <renderConfig v-if="item.type === 'renderConfig'"></renderConfig>
      <shadow v-if="item.type === 'shadows'"></shadow>
      <flood v-if="item.type === 'flood'" :layerId="item.id"></flood>
    </div>
  </div>
</template>

<script setup>
import {
  onMounted,
  onUnmounted,
  ref,
  reactive,
  defineProps,
  defineEmits
} from "vue";
import {
  addSenceImage,
  updateSenceImage,
  deleteSenceImage,
  getSenceImageByUserId
} from "../../api/collect";
import tile from "./components/tile.vue";
import model from "./components/model.vue";
import rootCollection from "./components/rootCollection.vue";
import normalCollection from "./components/normalCollection.vue";
import surfaceTransparency from "./components/surfaceTransparency.vue";
import tileLoadingConfig from "./components/tileLoadingConfig/index.vue";
import renderConfig from "./components/renderConfig.vue"
import shadow from "./components/shadow.vue"
import flood from "./components/flood.vue"
import SvgIcon from "../../components/SvgIcon.vue";
import { globalTool } from "../../../static/CIM/BQGIS-globalVar.js";
import bindContextmenu from "./bindContextmenu.js";
import { ElMessage } from "element-plus";
import { getUserSence } from "../../api/login";
import { getSceneList } from "../../api/system";
import { imageFileUpload } from "../../api/file.js";
import { base64toFile } from "../../../static/CIM/BQGIS-downBase64";
import { useStore } from "../../store/store";

const props = defineProps({
  isRoot: {
    // 是否是管理员
    type: Boolean
  }
});
const store = useStore();
const collectionDom = ref([]);
const setCollectionDom = el => {
  collectionDom.value.push(el);
};

bindContextmenu(viewer, props.isRoot);

const menuList = ref([]);
const currentMenu = ref({});
const collapse = ref(false); // 菜单是否折叠

function onClose(id) {
  const index = menuList.value.findIndex(item => item.id === id);
  if (index === -1) return;
  if (menuList.value.length === 1) {
    menuList.value = [];
    currentMenu.value = {};
  } else {
    menuList.value.splice(index, 1);
    currentMenu.value = menuList.value[0];
  }
}

function onCloseAll() {
  menuList.value = [];
  currentMenu.value = {};
}

function onSel(data) {
  collapse.value = false;
  currentMenu.value = data;
}

function openMenu(data) {
  const index = menuList.value.findIndex(item => item.id === data.id);
  if (index === -1) {
    // 避免重复添加菜单
    menuList.value.push(data);
  }
  currentMenu.value = data;
}

// 右键model，点击编辑菜单
globalTool.eventTarget.on("startEditModel", function(e) {
  openMenu({
    type: e.graphic.type,
    id: e.graphic.id,
    name: e.graphic.name
  });
});

// 右键3dtiles，点击编辑菜单
globalTool.eventTarget.on("startEditTile", function(e) {
  openMenu({
    type: e.layer.type,
    id: e.layer.id,
    name: e.layer.name
  });
});

globalTool.eventTarget.on("flood", function(e) {
  openMenu({
    type: "flood",
    id: "flood" + e.layer.id,
    name: e.layer.name + '水淹模拟'
  });
});

globalTool.eventTarget.on("tileLoadingConfig", function(e) {
  openMenu({
    type: "tileLoadingConfig",
    id: "TileLoadConfig" + e.layer.id,
    name: e.layer.name + '加载参数配置'
  });
});

globalTool.eventTarget.on("renderConfig", function(e) {
  openMenu({
    type: "renderConfig",
    id: "renderConfig",
    name: "渲染设置"
  });
});

// 关闭模型编辑菜单
globalTool.eventTarget.on("endEditModel", function(e) {
  // onClose(e.layer.id);
});

// 下载图片
globalTool.eventTarget.on("startDownImg", function() {
  ElMessage({
    message: "正在生成图片"
  });
  viewer
    .expImage({ type: "image/png" })
    .then(e => {
      ElMessage({
        message: "下载完成"
      });
    })
    .catch(err => {
      console.error(err);
      ElMessage({
        message: "生成图片失败"
      });
    });
});

// 添加收藏
globalTool.eventTarget.on("startCollect", function() {
  ElMessage({
    message: "正在生成图片"
  });
  const cartographic = viewer.camera.positionCartographic;
  viewer
    .expImage({ download: false, type: "image/png" })
    .then(e => {
      const f = new FormData();
      const file = base64toFile(e.image, dateFormat());
      f.append("file", file);
      f.append("module", "collect");
      return imageFileUpload(f);
    })
    .then(res => {
      ElMessage({
        message: "正在添加收藏"
      });
      const data = {
        name: dateFormat(),
        userId: store.loginInfo.id,
        url: res.path,
        camerapose: JSON.stringify({
          position: viewer.camera.position,
          lngLatPoint: {
            lng: Cesium.Math.toDegrees(cartographic.longitude),
            lat: Cesium.Math.toDegrees(cartographic.latitude),
            alt: cartographic.height
          },
          heading: Cesium.Math.toDegrees(viewer.camera.heading),
          pitch: Cesium.Math.toDegrees(viewer.camera.pitch),
          roll: Cesium.Math.toDegrees(viewer.camera.roll)
        })
      };
      return addSenceImage(data);
    })
    .then(() => {
      ElMessage({
        message: "收藏完成"
      });
      collectionDom.value.forEach(element => {
        element.getUserCollection();
      });
    })
    .catch(err => {
      console.error(err);
      ElMessage({
        message: "收藏图片失败"
      });
    });
});

// 打开收藏夹
globalTool.eventTarget.on("openFavorites", function() {
  openMenu({
    type: "favorites",
    id: "favorites",
    name: "收藏夹"
  });
});

// 日照分析
globalTool.eventTarget.on("shadows", function(e) {
  e.layer.tileset.shadows = Cesium.ShadowMode.ENABLED
  openMenu({
    type: "shadows",
    id: "shadows",
    name: "日照分析"
  });
});

// 地表透明度
globalTool.eventTarget.on("surfaceTransparency", function() {
  openMenu({
    type: "surfaceTransparency",
    id: "surfaceTransparency",
    name: "地表透明度"
  });
});

function dateFormat(date = new Date(), fmt = "YYYY-mm-dd HH:MM:SS") {
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "H+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "S+": date.getSeconds().toString() // 秒
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
      );
    }
  }
  return fmt;
}
</script>

<style lang="scss" scoped>
.container {
  position: absolute;
  top: 100px;
  border-radius: 10px;
  z-index: 20;
  background: linear-gradient(
    180deg,
    rgba(12, 49, 75, 0.6) 0%,
    rgba(0, 0, 0, 0.6) 100%
  );
  .header {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    padding: 10px;
    box-sizing: border-box;
    background: linear-gradient(
      180deg,
      rgba(12, 49, 75, 0.6) 0%,
      rgba(0, 0, 0, 0.6) 100%
    );
  }
  .select {
    color: #fff;
    cursor: pointer;
    margin-right: 10px;
  }
}
</style>